<?php
namespace app\index\controller;

use think\Controller;
use think\Db;
use think\Session;
use app\index\validate\User as UserValidate;
class Index extends Controller
{
    public function login()
    {
        return $this->fetch('index/login');
    }
    public function register()
    {
        $AllClass = Db::name('class')->select();
        $this->assign('class',$AllClass);
        return $this->fetch();
    }

    /**
     * 注册方法
     */
    public function insert()
    {
        $data = input('post.');
        $val = new UserValidate();
        if (!$val->check($data)) {
            $this->error($val->getError());
            exit();
        }
        $chk = Db::name('person')->where('name',$data['name'])->find();
        if ($chk>0){
            $this->error('用户名已被注册');
        }
        $class=$data['class'];
        unset($data['class']);
        $ret = Db::name('person')->insert($data);
//        $user = new UserModel($data);
//        $ret = $user->allowField(true)->save();
        //        $user = new UserModel($data);
//        $ret = $user->allowField(true)->save();
         $resultP=Db::name('person')->where('name',$data['name'])->find();
         $resultC=Db::name('class')->where('name',$class)->find();
        $classPer['class_id']=$resultC['class_id'];
         $classPer['person_id']=$resultP['person_id'];
         $ret2=Db::name('classperson')->insert($classPer);
        if ($ret&&$ret2) {
            $this->success('新增用户成功', 'index/Index/login');
        } else {
            $this->error('新增用户失败');
        }
    }

    /**
     * 登陆方法
     */
    public function check()
    {
        $data = input('post.');
        $result = Db::name('person')->where('name',$data['name'])->find();
        $res = Db::name('user')->where('name',$data['name'])->find();
//        $user = new UserModel();
//        $result = $user->where('name', $data['name'])->find();
        if ($result||$res) {
            if ($result['password'] === $data['password']||$res['password']=== md5($data['password'])) {
                if ($res){
                    session('name',$data['name']);
                    session('status',$res['status']);
                    session('user_id',$res['user_id']);
                    Session::set('user_id',$res['user_id']);
                    $this->redirect( '/index/User/index');
                }else {
//                    $this->error('已关闭');
                    session('name', $data['name']);
                    session('person_id',$result['person_id']);
                    session('status',$result['status']);
                    $this->redirect('/index/Person/index');
                }
            } else {
                $this->error('密码错误');
            }
        } else {
            $this->error('用户名不存在');
            exit();
        }
    }
    public function logout()
    {
        session(null);
        $this->redirect('Index/login');
    }
}
